package xhwl.hmo.mall.ui;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import xhwl.hmo.mall.BaseActivity;
import xhwl.hmo.mall.IntentConstants;
import xhwl.hmo.mall.R;
import xhwl.hmo.mall.adapter.InfoOderSuitesAdapter;
import xhwl.hmo.mall.adapter.OrderCommentAdapter;
import xhwl.hmo.mall.bean.GoodType;
import xhwl.hmo.mall.event.OrderStateChangeEvent;
import xhwl.hmo.mall.http.api.CancelOrderApi;
import xhwl.hmo.mall.http.api.ConfirmReceiptApi;
import xhwl.hmo.mall.http.api.GetOrderDetailApi;
import xhwl.hmo.mall.http.bean.resp.HttpResp;
import xhwl.hmo.mall.http.bean.resp.OrderDetailResp;
import xhwl.hmo.mall.utils.AlarmUtil;
import xhwl.hmo.mall.utils.AppUtil;
import xhwl.hmo.mall.utils.IdcardValidator;
import xhwl.hmo.mall.utils.StringUtil;
import xhwl.hmo.mall.views.GridViewforScrollView;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;

/**
 * 商城订单详情页面
 */
public class InfoOrderActivity extends BaseActivity implements View.OnClickListener {
    private static final int REQUEST_CODE_ADD_COMMENT = 0;
    private static final int REQUEST_CODE_CANCLE_ORDER = 1;
    public static final String EXTRA_ORDER_ID = "orderId";
    private TextView name_receiver;
    private TextView address_receiver;
    private TextView phone_receiver;
    private RelativeLayout info_receiver_layout;
    private ImageView card_pic;
    private TextView name_card;
    private TextView desc_card;
    private TextView tvPrice;
    private TextView tvPrice_original;
    private GridViewforScrollView gridview;
    private TextView name_baozhang;
    private TextView phone_baozhang;
    private TextView id_baozhang;
    private TextView num_order;
    private TextView name_delivery;
    private TextView time_order_place;
    private TextView num_delivery;
    private TextView time_pay;
    private RecyclerView mRecyclerView;
    private TextView num_pay;
    private TextView order_cancel;
    private TextView pay_start;
    private RelativeLayout recycler_layout;
    List<OrderDetailResp.COMMENTINFOBean> mList = new ArrayList<>();//评论
    List<OrderDetailResp.DEV_INFOBean> suitesList = new ArrayList<>();//套装内容
    private OrderCommentAdapter adapter;
    private InfoOderSuitesAdapter suitesAdapter;//套装内容
    private String order_id = "";
    //    private String goods_type = "";
//    private String ORDER_STATUS = "";
    OrderDetailResp.ORDERINFOBean data;
    private TextView comment_make;
    private TextView receive_assure;
    private LinearLayout orderstatus_layout;
    private TextView order_status;
    private TextView time_order_close;//还有多久关闭时间

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        order_id = getIntent().getStringExtra(EXTRA_ORDER_ID);
//        goods_type = getIntent().getStringExtra("goods_type");
//        ORDER_STATUS = getIntent().getStringExtra("ORDER_STATUS");
        setContentView(R.layout.activity_info_order);
    }

    @Override
    public void initViews() {
        initTitleViews();
        initView();

    }

    @Override
    protected void setUpTitleView() {
        super.setUpTitleView();
        titleTextView.setText("订单详情");
    }

    @Override
    public void initListener() {
        order_cancel.setOnClickListener(this);
        pay_start.setOnClickListener(this);
        receive_assure.setOnClickListener(this);
        comment_make.setOnClickListener(this);
    }

    @Override
    protected void processOper() {
        super.processOper();
        initRecylerView();
        adapter = new OrderCommentAdapter(this, mList);//评价内容
        mRecyclerView.setAdapter(adapter);
        suitesAdapter = new InfoOderSuitesAdapter(this, suitesList);//评价内容
        gridview.setAdapter(suitesAdapter);
    }

    @Override
    public void loadData() {
        getOrderDetails(order_id);
    }

    public void setButtonVisible(String goods_type, String ORDER_STATUS) {
        if ("待评价".equals(ORDER_STATUS)) {
            comment_make.setVisibility(View.VISIBLE);
            orderstatus_layout.setBackground(getResources().getDrawable(R.drawable.img_comment_wait));
            order_status.setText("待评价");
        }
        else if ("待收货".equals(ORDER_STATUS)) {
            receive_assure.setVisibility(View.VISIBLE);
            orderstatus_layout.setBackground(getResources().getDrawable(R.drawable.img_recive_wait));
            order_status.setText("待收货");
            time_order_close.setVisibility(View.VISIBLE);
        }
        else if ("待付款".equals(ORDER_STATUS)) {
            if (goods_type.equals(GoodType.TZ)) {
                info_receiver_layout.setVisibility(View.VISIBLE);
            } else {
                info_receiver_layout.setVisibility(View.GONE);
            }
            order_cancel.setVisibility(View.VISIBLE);
            pay_start.setVisibility(View.VISIBLE);
            orderstatus_layout.setBackground(getResources().getDrawable(R.drawable.img_pay_wait));
            order_status.setText("待付款");
            time_order_close.setVisibility(View.VISIBLE);
        }
        else if ("已完成".equals(ORDER_STATUS)) {
            orderstatus_layout.setBackground(getResources().getDrawable(R.drawable.img_comment_wait));
            order_status.setText("已完成");
        }
        else if ("待发货".equals(ORDER_STATUS)) {
            orderstatus_layout.setBackground(getResources().getDrawable(R.drawable.img_delivery_wait));
            order_status.setText("待发货");
        }
        else if ("已过期".equals(ORDER_STATUS)) {
            orderstatus_layout.setBackground(getResources().getDrawable(R.drawable.img_outdate));
            order_status.setText("已过期");
        }
        else  if ("已取消".equals(ORDER_STATUS)) {
            orderstatus_layout.setBackground(getResources().getDrawable(R.drawable.img_outdate));
            order_status.setText("已取消");
        }
    }

    //goods_type / /商品类别 1健康套装系列 2重疾卡系列 3HMO卡系列 0设备
    private void getOrderDetails(String order_id) {
        GetOrderDetailApi api = new GetOrderDetailApi(order_id);
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<HttpResp<OrderDetailResp>>() {
            @Override
            public void onNext(HttpResp<OrderDetailResp> resp) {
                if (null != resp.data && resp.data.getORDER_INFO().size() > 0) {
                    setData(resp.data.getORDER_INFO().get(0));//设置订单信息
                }
                if (null != resp.data && resp.data.getCOMMENT_INFO().size() > 0) {
                    mList.addAll(resp.data.getCOMMENT_INFO());//设置订单评论详情
                    adapter.notifyDataSetChanged();
                }
                if (null != resp.data && resp.data.getDEV_INFO().size() > 0) {
                    suitesList.addAll(resp.data.getDEV_INFO());//套装内容
                    suitesAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    private void setData(OrderDetailResp.ORDERINFOBean resp) {
        this.data = resp;
        setButtonVisible(resp.getGOODS_TYPE(), resp.getORDER_STATUS());
        if (StringUtil.isEmpty(resp.getSH_NAME()) || StringUtil.isEmpty(resp.getSH_MOBILE()) || StringUtil.isEmpty(resp.getSH_ADDRESS())) {
            info_receiver_layout.setVisibility(View.GONE);
        }
        name_receiver.setText("收货人: " + resp.getSH_NAME());
        phone_receiver.setText(resp.getSH_MOBILE());
        address_receiver.setText(resp.getPROVINCE_NAME() + " " + resp.getCITY_NAME() + "\n" + resp.getSH_ADDRESS());
        Glide.with(this).load(resp.getGOODS_PIC())
                .error(R.drawable.logo)
                .into(card_pic);
        if (resp.getGOODS_NAME().contains("套装")) {
            String name_goods = resp.getGOODS_NAME();
            String[] strings = name_goods.split("卡");
            name_card.setText(strings[0] + "卡");
            desc_card.setText(strings[1].trim());
        } else {
            name_card.setText(resp.getGOODS_NAME());
        }
        tvPrice.setText("￥" + resp.getGOODS_SALE_MONEY() + "/年");
        tvPrice_original.setText("￥" + resp.getGOODS_MONEY() + "/年");
        name_baozhang.setText(resp.getPERSON_NAME());
        if (!StringUtil.isEmpty(resp.getPERSON_IDCARD())) {
            String iscardinfo = IdcardValidator.validate18Idcard(resp.getPERSON_IDCARD());
            if (StringUtil.isEmpty(iscardinfo)) {
                id_baozhang.setText(resp.getPERSON_IDCARD());
            } else {
                id_baozhang.setText("暂未填写");
            }
        } else {
            id_baozhang.setText("暂未填写");
        }
        phone_baozhang.setText(resp.getPERSON_MOBILE());
        num_order.setText("订单号: " + resp.getORDER_ID());
        if (!resp.getLOGISTICS().equals("")) {
            name_delivery.setText("物流名称: " + resp.getLOGISTICS());//物流名称
        }
        if (!resp.getWL_CODE().equals("")) {
            num_delivery.setText("物流单号: " + resp.getWL_CODE());//物流单号
        }
        if (null != resp.getCREATE_DATE() && "" != resp.getCREATE_DATE()) {
            time_order_place.setText("下单时间: " + timeFormat(resp.getCREATE_DATE()));//下单时间
        }
        if (null != resp.getPAY_TIME() && "" != resp.getPAY_TIME()) {
            time_pay.setText("支付时间: " + timeFormat(resp.getPAY_TIME()));//支付时间
        }
        if ("待付款".equals(resp.getORDER_STATUS()) || "已过期".equals(resp.getORDER_STATUS())|| "已取消".equals(resp.getORDER_STATUS())) {
            String pay_sum = "应付金额: ￥" + resp.getORDER_MONEY();
            SpannableString spannableString = new SpannableString(pay_sum);
            spannableString.setSpan(new AbsoluteSizeSpan(60), 6, pay_sum.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannableString.setSpan(new ForegroundColorSpan(Color.RED), 6, pay_sum.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); //设置背景色为青色 ;
            num_pay.setText(spannableString);
        } else {
            String pay_sum = "已付金额: ￥" + resp.getORDER_MONEY();
            SpannableString spannableString = new SpannableString(pay_sum);
            spannableString.setSpan(new AbsoluteSizeSpan(60), 6, pay_sum.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannableString.setSpan(new ForegroundColorSpan(Color.RED), 6, pay_sum.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); //设置背景色为青色 ;
            num_pay.setText(spannableString);
        }
        if (!StringUtil.isEmpty(data.getAR_DATE())) {
            int hours = Math.abs(Integer.parseInt(resp.getAR_DATE()));
            if ("待收货".equals(resp.getORDER_STATUS())) {
                time_order_close.setText("剩" + hours / 24 + "天" + hours % 24 + "小时自动确认");
            } else if ("待付款".equals(resp.getORDER_STATUS())) {
                time_order_close.setText("剩" + hours / 24 + "天" + hours % 24 + "小时自动关闭");
            }
        } else {
            time_order_close.setVisibility(View.GONE);
        }
    }


    private void initView() {
        name_receiver = (TextView) findViewById(R.id.name_receiver);
        address_receiver = (TextView) findViewById(R.id.address_receiver);
        phone_receiver = (TextView) findViewById(R.id.phone_receiver);
        info_receiver_layout = (RelativeLayout) findViewById(R.id.info_receiver_layout);
        card_pic = (ImageView) findViewById(R.id.card_pic);
        name_card = (TextView) findViewById(R.id.name_card);
        desc_card = (TextView) findViewById(R.id.desc_card);
        tvPrice = (TextView) findViewById(R.id.tvPrice);
        tvPrice_original = (TextView) findViewById(R.id.tvPrice_original);
        gridview = (GridViewforScrollView) findViewById(R.id.gridview);
        name_baozhang = (TextView) findViewById(R.id.name_baozhang);
        phone_baozhang = (TextView) findViewById(R.id.phone_baozhang);
        id_baozhang = (TextView) findViewById(R.id.id_baozhang);
        num_order = (TextView) findViewById(R.id.num_order);
        name_delivery = (TextView) findViewById(R.id.name_delivery);
        time_order_place = (TextView) findViewById(R.id.time_order_place);
        num_delivery = (TextView) findViewById(R.id.num_delivery);
        time_pay = (TextView) findViewById(R.id.time_pay);
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        num_pay = (TextView) findViewById(R.id.num_pay);
        order_cancel = (TextView) findViewById(R.id.order_cancel);
        pay_start = (TextView) findViewById(R.id.pay_start);
        comment_make = (TextView) findViewById(R.id.comment_make);
        receive_assure = (TextView) findViewById(R.id.receive_assure);
        recycler_layout = (RelativeLayout) findViewById(R.id.recycler_layout);
        orderstatus_layout = (LinearLayout) findViewById(R.id.orderstatus_layout);
        order_status = (TextView) findViewById(R.id.order_status);
        time_order_close = (TextView) findViewById(R.id.time_order_close);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.order_cancel:
                //取消订单
                cancelOrder(order_id);
                break;
            case R.id.comment_make:
                //评价
                Intent intent = new Intent(mContext, AddCommentActivity.class);
                intent.putExtra(AddCommentActivity.EXTRA_BUY_ID, data.getBUY_ID());
                intent.putExtra(AddCommentActivity.EXTRA_GOOD_ID, data.getGOODS_ID());
                startActivityForResult(intent, REQUEST_CODE_ADD_COMMENT);
                break;
            case R.id.receive_assure:
                //确认收货
                confirmReceipt(data.getBUY_ID());
                break;
            case R.id.pay_start:
                //立即付款
                AppUtil.startPayment(this, data.getORDER_ID(), data.getGOODS_NAME(), data.getORDER_MONEY());
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_ADD_COMMENT && requestCode == RESULT_OK) {
            finish();
        }
    }

    private void cancelOrder(final String order_id) {
        CancelOrderApi api = new CancelOrderApi(order_id);
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<HttpResp>() {
            @Override
            public void onNext(HttpResp resp) {
                if (null != resp) {
                    if (resp.isOk()) {
                        Toast.makeText(InfoOrderActivity.this, "订单删除成功", Toast.LENGTH_LONG).show();
                        //取消闹钟
                        AlarmUtil.cancelAlarm(InfoOrderActivity.this, IntentConstants.Action.orderRemind, Integer.parseInt(order_id));

                        EventBus.getDefault().post(new OrderStateChangeEvent());
                        finish();
                    } else {
                        Toast.makeText(InfoOrderActivity.this, resp.message, Toast.LENGTH_LONG).show();
                    }
                }
            }
        });
    }

    private void initRecylerView() {
        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView mRecyclerView, int dx, int dy) {
                super.onScrolled(mRecyclerView, dx, dy);
            }
        });
    }

    private String timeFormat(String create_date) {
        // 2017-10-18 15:39:01
        String[] dates = create_date.split(" ");
        String[] datess = dates[0].split("-");
        String year = datess[0].substring(2, 4);
        String[] time = dates[1].split(":");
        return year + "/" + datess[1] + "/" + datess[2] + " " + time[0] + ":" + time[1];
    }

    private void confirmReceipt(String buy_id) {
        ConfirmReceiptApi api = new ConfirmReceiptApi(buy_id);
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<HttpResp>() {
            @Override
            public void onNext(HttpResp resp) {
                if (null != resp) {
                    if (resp.isOk()) {
                        Toast.makeText(InfoOrderActivity.this, "确认收货成功", Toast.LENGTH_LONG).show();
                        receive_assure.setVisibility(View.GONE);
                    } else {
                        Toast.makeText(InfoOrderActivity.this, resp.message, Toast.LENGTH_LONG).show();
                    }
                }
            }
        });

    }
}
